from django import http
from django.utils import datastructures

class LazyPUT(object):
    def __get__(self, request, owner):
        # attribute sim_method is set in Collection.__call__
        method = hasattr(request, 'sim_method') and request.sim_method or request.method
        if method != 'PUT':
            return http.QueryDict('')
        if not hasattr(request, '_put'):
            # wsgi
            if hasattr(request, 'environ') \
                    and request.environ.get('CONTENT_TYPE', '').startswith('multipart'):
                header_dict = dict([(k, v) for k, v in request.environ.items() if k.startswith('HTTP_')])
                header_dict['Content-Type'] = request.environ.get('CONTENT_TYPE', '')
                request._put, request._files = http.parse_file_upload(header_dict, request.raw_post_data)
            # modpython
            elif hasattr(request, '_req') \
                    and request._req.headers_in.has_key('content-type') \
                    and request._req.headers_in['content-type'].startswith('multipart'):
                self._put, self._files = http.parse_file_upload(self._req.headers_in, self.raw_post_data)
            else:
                request._put, request._files = http.QueryDict(request.raw_post_data), datastructures.MultiValueDict()
            # ? should we set the POST empty ?
            #request._post = datastructures.MultiValueDict()
            request._post = request._put

        return request._put

    def __set__(self, request, value):
        request._put = value

class ProcessPutData(object):
    def process_request(self, request):
        request.__class__.PUT = LazyPUT()
